import {defineStore} from "pinia"
import {ref, computed} from "vue"
import {useUserStore} from './user.js'
import {insertCartApi, findNewCartListApi, deleteCartApi} from "@/apis/cart.js"

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userDate.token)
  const cartList = ref([])
  let selectAll = computed(() => cartList.value.every(item => item.selected === true))
  //添加商品到购物车
  const addToCart = async (goods) => {
    const {skuId, count} = goods
    if(isLogin.value) {//已登录,储存到服务器
      await insertCartApi({skuId, count})
      const res = await findNewCartListApi()
      cartList.value = res.result
    }else{//未登录,储存到本地
      //通过cartList的skuId属性判断是否已经存在该商品，如果存在，则数量+1，如果不存在，则添加到购物车
      const item = cartList.value.find(item => item.skuId === goods.skuId)
      if(item){
        item.count += goods.count
      }else{
        cartList.value.push(goods)
      }
    }
  }
  const delCart = async (skuId) => {
    if(isLogin.value) {
      await deleteCartApi([skuId])
      const res = await findNewCartListApi()
      cartList.value = res.result
      console.log(res.result)
    }else {
      //通过下标删除商品
      const index = cartList.value.findIndex(item => item.skuId === skuId)
      if(index!== -1){
        cartList.value.splice(index, 1)
      }
      //filter方法删除商品
      // cartList.value = cartList.value.filter(item => item.skuId!== kuId)
    }
  }
  //计算总数
  const countTotal = computed(() => cartList.value.reduce((acc, cur) => acc + cur.count, 0))
  //计算总价
  const countPrice = computed(() => cartList.value.reduce((acc, cur) => acc + cur.price * cur.count, 0))
  const buyList = computed(() => cartList.value.filter(item => item.selected === true))
  const payPrice = computed(() => buyList.value.reduce((acc, cur) => acc + cur.price * cur.count, 0))
  const payTotal = computed(() => buyList.value.reduce((acc, cur) => acc + cur.count, 0))
  //全选/全不选
  const selectedAll = () => {
      if(selectAll.value){
        cartList.value.forEach(item => item.selected = false)
      }else{
        cartList.value.forEach(item => item.selected = true)
      }
  }
  const reCartList = async () => {
      const res = await findNewCartListApi()
      cartList.value = res.result
  }
  const clearCart = () => {
    cartList.value = []
  }
  const pushCart = () => {

  }
  return {
    cartList,
    countTotal,
    countPrice,
    payPrice,
    payTotal,
    selectAll,
    addToCart,
    delCart,
    selectedAll,
    reCartList,
    clearCart,
    pushCart,

  }
},{
  persist: true,
})
